package com.blacamdk.ChatNetModule;

import com.blacamdk.ChatSecret.Blowfish;

import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Arrays;

/**
 * UDPClient
 *
 * @author BlacAmDK
 * @date 16-12-20
 */
public class UDPClient {
    private DatagramSocket datagramSocket = null; // 连接对象
    private byte[] send;
    public String sendData(String s) {
        try {
            send = s.getBytes("UTF-8");
            if(!init()) throw new Exception("UPD连接初始化失败");
            byte[] buffer = new byte[1024 * 64]; // 缓冲区
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(ClientMain.server), ClientMain.port);
            packet.setData(send);
            try {
                sendDate(packet);
            } catch(Exception e){
                e.printStackTrace();
            }
            receive(packet);
            send = new byte[packet.getLength()];
            System.arraycopy(packet.getData(), 0, send, 0, packet.getLength());
            String ret = new String(send);
            if(send.length > 0){
                if(Utils.isNumeric(ret.split(" ")[0]))//第一字段以数字开头，符合正常数据
                    return ret;
            }
        } catch (SocketTimeoutException e) {
            return "99 TIMEOUT";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 接收数据包，该方法会造成线程阻塞
     */
    private void receive(DatagramPacket packet) throws Exception {
        datagramSocket.receive(packet);
    }
    /**
     * 发送数据包到指定地点
     */
    private void sendDate(DatagramPacket packet) {
        try {
            datagramSocket.send(packet);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 初始化客户端连接
     */
    private boolean init() throws SocketException {
        try {
            datagramSocket = new DatagramSocket();
            datagramSocket.setSoTimeout(10 * 1000);
            return true;
        } catch (Exception e) {
            datagramSocket = null;
        }
        return false;
    }
}